<template>
  <CDialog
    :visible="visible"
    title="修改支付信息"
    type="add"
    width="630px"
    @submit="handleSubmit"
    @cancel="handleCancel"
  >
    <i-form
      :items="items"
      :model="form"
      :rules="rules"
      label-width="150px"
      size="small"
      ref="form"
    >
      <template slot="splitValue">
        <el-form-item v-if="showSplitValue" label="分账比例" prop="splitValue">
          <div style="display: flex">
            <el-input placeholder="请输入分账比例" v-model="form.splitValue" />
            <span>%</span>
          </div>
        </el-form-item>
      </template>
      <template slot="payment">
        <el-form-item label="商户支付">
          <el-checkbox v-model="form.visible" />
          <!-- <el-checkbox v-model="visible"/> -->
        </el-form-item>
      </template>
      <template slot="small">
        <el-form-item
          :class="{ 'merchant-detail-payment_bottom': !form.small }"
          v-if="form.visible && form.paymentChannels === '0,1,4'"
          label="小微商户:"
        >
          <el-checkbox v-model="form.small" />
          <!-- <el-checkbox v-model="small"/> -->
        </el-form-item>
      </template>
      <template
        slot="aliPayment"
        v-if="this.$store.getters.userData.type != 'SELF_OPERATION_ADMIN'"
      >
        <el-form-item style="border-top: 1px solid #000" label="支付宝支付:">
          <el-checkbox v-model="form.aliVisible" />
          <!-- <el-checkbox v-model="aliVisible"/> -->
        </el-form-item>
      </template>
      <template
        slot="mobilePayment"
        v-if="this.$store.getters.userData.type != 'SELF_OPERATION_ADMIN'"
      >
        <el-form-item style="border-top: 1px solid #000" label="移动话费支付">
          <el-checkbox v-model="form.mobileVisible" />
        </el-form-item>
      </template>
    </i-form>
  </CDialog>
</template>
<script>
import CDialog from '@/components/CDialog'
import { cloneDeep, isString } from 'lodash'
import { updateMerchantPayment } from '@/api/user'
import Big from 'big.js'

export default {
  name: 'ChangePaymentDlg',
  components: { CDialog },
  computed: {
    showSplitValue() {
      let bol =
        this.form.paymentChannels === '0,1,4' &&
        this.userType == 'SELF_OPERATION_MERCHANT'
      return bol
    },
  },
  data() {
    return {
      userType: '',
      form: {},
      items: [
        {
          slot: 'payment',
        },
        {
          label: '商户模式:',
          type: 'radio',
          value: 'paymentChannels',
          hidden: true,
          options: [
            {
              text: '中移账户商户',
              label: '8,9,10',
            },
            {
              text: '子商户',
              label: '0,1,4',
            },
            {
              text: '光大银联',
              label: '5,6,7',
            },
          ],
        },
        {
          slot: 'splitValue',
        },
        {
          slot: 'small',
        },
        {
          label: '子商户APPID:',
          type: 'text',
          value: 'weixinSubAppid',
          hidden: true,
        },
        {
          label: '微信子商户号:',
          type: 'text',
          value: 'weixinSubMchId',
          hidden: true,
        },
        {
          label: '微信退款授权:',
          type: 'checkbox',
          value: 'refund',
          hidden: true,
          options: [
            {
              label: '1',
              text: '授权',
            },
          ],
        },
        {
          label: '银联门店ID:',
          type: 'text',
          value: 'unionpayOpenId',
          hidden: true,
        },
        {
          label: '银联支付密钥:',
          type: 'text',
          value: 'unionpayOpenKey',
          hidden: true,
        },
        {
          label: '银联商户主密码:',
          type: 'text',
          value: 'unionpayShopPass',
          hidden: true,
        },
        {
          label: '银联退款授权:',
          type: 'checkbox',
          value: 'refund',
          hidden: true,
          options: [
            {
              label: '1',
              text: '授权',
            },
          ],
        },
        {
          slot: 'aliPayment',
        },
        {
          label: '结算方式:',
          value: 'jiesuan',
          type: 'radio',
          hidden: true,
          options: [
            {
              text: '支付宝',
              label: '支付宝',
            },
            {
              text: '银行卡',
              label: '银行卡',
            },
          ],
        },
        {
          label: '支付宝账号:',
          type: 'text',
          hidden: true,
          value: 'aliLoginName',
        },
        {
          label: '商户银行卡号:',
          type: 'text',
          hidden: true,
          value: 'cardAliasNo',
        },
        {
          label: '二级商户号:',
          type: 'text',
          hidden: true,
          value: 'aliExternalId',
        },
        {
          slot: 'mobilePayment',
        },
        {
          type: 'text',
          label: '移动支付商户ID:',
          hidden: true,
          value: 'smsMchId',
        },
      ],
      rules: {},
    }
  },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    defaultForm: {
      type: Object,
      required: true,
    },
  },
  mounted() {
    let tempForm = {
      ...this.defaultForm,
    }

    this.userType = this.defaultForm.type
    let paymentArr = this.tranformChannelsToArray(tempForm.paymentChannels)

    if (this.userType === 'SELF_OPERATION_MERCHANT') {
      this.items = [
        {
          slot: 'payment',
        },
        {
          label: '商户模式:',
          type: 'radio',
          value: 'paymentChannels',
          hidden: true,
          options: [
            {
              text: '子商户',
              label: '0,1,4',
            },
          ],
        },
        {
          slot: 'splitValue',
        },
        {
          slot: 'small',
        },
        {
          label: '子商户APPID:',
          type: 'text',
          value: 'weixinSubAppid',
          hidden: true,
        },
        {
          label: '微信子商户号:',
          type: 'text',
          value: 'weixinSubMchId',
          hidden: true,
        },
        {
          label: '微信退款授权:',
          type: 'checkbox',
          value: 'refund',
          hidden: true,
          options: [
            {
              label: '1',
              text: '授权',
            },
          ],
        },
      ]
    }

    if (
      (paymentArr.findIndex((item) => item == '2') !== -1 ||
        paymentArr.findIndex((item) => item == '11') !== -1) &&
      (tempForm.cardAliasNo || tempForm.aliExternalId)
    ) {
      tempForm.aliVisible = true
      tempForm.jiesuan = '银行卡'
    }

    if (
      (paymentArr.findIndex((item) => item == '2') !== -1 ||
        paymentArr.findIndex((item) => item == '11') !== -1) &&
      (tempForm.aliLoginName || tempForm.aliExternalId)
    ) {
      tempForm.aliVisible = true
      tempForm.jiesuan = '支付宝'
    }

    if (
      paymentArr.findIndex((item) => item == '13') !== -1 &&
      tempForm.smsMchId
    ) {
      tempForm.mobileVisible = true
    }

    if (!isString(tempForm.paymentChannels)) return
    if (
      paymentArr.findIndex((item) => item == '8') !== -1 ||
      paymentArr.findIndex((item) => item == '9') !== -1 ||
      paymentArr.findIndex((item) => item == '10') !== -1
    ) {
      tempForm.visible = true
      tempForm.paymentChannels = '8,9,10'
    } else if (
      paymentArr.findIndex((item) => item == '0') !== -1 ||
      paymentArr.findIndex((item) => item == '1') !== -1 ||
      paymentArr.findIndex((item) => item == '4') !== -1
    ) {
      tempForm.visible = true
      tempForm.paymentChannels = '0,1,4'
    } else if (
      paymentArr.findIndex((item) => item == '5') !== -1 ||
      paymentArr.findIndex((item) => item == '6') !== -1 ||
      paymentArr.findIndex((item) => item == '7') !== -1
    ) {
      tempForm.visible = true
      tempForm.paymentChannels = '5,6,7'
    }

    if (tempForm.refund) {
      tempForm.refund = ['1']
    }

    if (tempForm.splitValue) {
      tempForm.splitValue = Big(tempForm.splitValue).times(100)
    }
    this.form = cloneDeep(tempForm)
  },
  watch: {
    'form.visible': {
      handler(val) {
        // if (val === oldVal) return
        this.changeHidden('商户模式:', !val)
        if (!val) {
          this.form.paymentChannels = ''
        }
      },
      deep: true,
    },
    'form.paymentChannels': {
      handler(val) {
        // if (val === oldVal) return
        if (val === '5,6,7') {
          this.changeHidden('银联门店ID:', false)
          this.changeHidden('银联支付密钥:', false)
          this.changeHidden('银联商户主密码:', false)
          this.changeHidden('银联退款授权:', false)
        } else {
          this.changeHidden('银联门店ID:', true)
          this.changeHidden('银联支付密钥:', true)
          this.changeHidden('银联商户主密码:', true)
          this.changeHidden('银联退款授权:', true)
        }
        if (val !== '0,1,4') {
          this.changeHidden('子商户APPID:', true)
          this.changeHidden('微信子商户号:', true)
          this.changeHidden('微信退款授权:', true)

          if (this.userType === 'SELF_OPERATION_MERCHANT') {
            this.$set(this.rules, 'splitValue', [])
          }
        } else {
          if (!this.form.small) {
            this.changeHidden('子商户APPID:', false)
            this.changeHidden('微信子商户号:', false)
            this.changeHidden('微信退款授权:', false)
          } else {
            this.changeHidden('子商户APPID:', true)
            this.changeHidden('微信子商户号:', true)
            this.changeHidden('微信退款授权:', true)
          }

          if (this.userType === 'SELF_OPERATION_MERCHANT') {
            this.$set(this.rules, 'splitValue', [
              {
                required: true,
                validator: (rule, value, callback) => {
                  let reg = /^[1-9]\d*$/
                  if (!reg.test(value)) {
                    callback(new Error('请输入整数!'))
                  } else if (value < 70 || value > 100) {
                    callback(new Error('请输入大于70且小于等于100的整数！'))
                  } else {
                    callback()
                  }
                },
              },
            ])
          }
        }
      },
      deep: true,
    },
    'form.small': {
      handler(val) {
        // if (val === oldVal) return
        if (this.form.paymentChannels !== '0,1,4') return
        this.changeHidden('子商户APPID:', val)
        this.changeHidden('微信子商户号:', val)
        this.changeHidden('微信退款授权:', val)
      },
      deep: true,
    },
    'form.aliVisible': {
      handler(val) {
        // if (val === oldVal) return
        if (val) {
          this.changeHidden('结算方式:', false)
          this.changeHidden('二级商户号:', false)

          if (this.form.jiesuan === '支付宝') {
            this.changeHidden('支付宝账号:', false)
            this.changeHidden('商户银行卡号:', true)
          } else {
            this.changeHidden('支付宝账号:', true)
            this.changeHidden('商户银行卡号:', false)
          }
        } else {
          this.changeHidden('结算方式:', true)
          this.changeHidden('二级商户号:', true)
          this.changeHidden('支付宝账号:', true)
          this.changeHidden('商户银行卡号:', true)
        }
      },
    },
    'form.mobileVisible': {
      handler(val) {
        // if (val === oldVal) return
        this.changeHidden('移动支付商户ID:', !val)
      },
    },
    'form.jiesuan': {
      handler(val) {
        // if (val === oldVal) return
        if (!this.form.aliVisible) {
          this.changeHidden('支付宝账号:', true)
          this.changeHidden('商户银行卡号:', true)
          this.changeHidden('二级商户号:', true)
          return
        }
        if (val === '支付宝') {
          this.changeHidden('支付宝账号:', false)
          this.changeHidden('商户银行卡号:', true)
        } else {
          this.changeHidden('支付宝账号:', true)
          this.changeHidden('商户银行卡号:', false)
        }
      },
    },
  },
  methods: {
    handleSubmit() {
      let validate = true
      this.$refs.form.validate((valid) => {
        if (!valid) validate = false
      })

      if (!validate) return

      const tempForm = cloneDeep(this.form)
      const submitForm = {
        ...this.filterPaymentSubmit(tempForm),
        ...this.filterAliPayment(tempForm),
        ...this.filterMobilePayment(tempForm),
      }

      if (!submitForm.hasMerchantPayment) {
        submitForm.paymentChannels = ''
      }

      if (submitForm.hasAlipay) {
        submitForm.paymentChannels += ',2,11'
      }

      if (submitForm.hasMobilePayment) {
        submitForm.paymentChannels += ',13'
      }

      if (submitForm.paymentChannels.substr(0, 1) === ',') {
        submitForm.paymentChannels = submitForm.paymentChannels.substr(1)
      }

      delete submitForm.hasMerchantPayment
      delete submitForm.hasAlipay
      delete submitForm.hasMobilePayment

      if (!this.$route.params.userId) return

      submitForm.id = this.$route.params.userId

      updateMerchantPayment(submitForm).then(() => {
        this.$message({
          type: 'success',
          showClose: true,
          message: '操作成功',
        })

        this.$emit('refresh')
        this.$emit('update:visible', false)
      })
    },
    handleCancel() {
      this.$emit('update:visible', false)
    },
    filterPaymentSubmit(tempForm) {
      let form = {}

      if (!tempForm.visible) return {}

      switch (tempForm.paymentChannels) {
        case '0,1,4':
          if (!tempForm.small) {
            form = {
              //子商户appid
              // 微信子商户号
              // 授权
              weixinSubAppid: tempForm.weixinSubAppid,
              weixinSubMchId: tempForm.weixinSubMchId,
              refund: tempForm.refund.length > 0,
            }
          } else {
            form = {
              small: tempForm.small,
              paymentChannels: '0,4',
            }
          }

          if (this.userType === 'SELF_OPERATION_MERCHANT') {
            form.splitValue = parseFloat(Big(tempForm.splitValue).div(100))
            // form.splitValue = parseInt( tempForm.splitValue, 10)
          }
          break
        case '5,6,7':
          form = {
            unionpayOpenId: tempForm.unionpayOpenId,
            unionpayOpenKey: tempForm.unionpayOpenKey,
            unionpayShopPass: tempForm.unionpayShopPass,
            refund: tempForm.refund.length > 0,
          }
          break
        // case '':
        //   break;
        default:
          break
      }

      if (!form.paymentChannels) {
        form.paymentChannels = tempForm.paymentChannels
      }

      form.hasMerchantPayment = true
      return form
    },
    filterAliPayment(tempForm) {
      let form = {}
      if (!tempForm.aliVisible) return form

      switch (tempForm.jiesuan) {
        case '银行卡':
          form = {
            cardAliasNo: tempForm.cardAliasNo,
            aliExternalId: tempForm.aliExternalId,
          }
          break
        case '支付宝':
          form = {
            aliLoginName: tempForm.aliLoginName,
            aliExternalId: tempForm.aliExternalId,
          }
          break
        default:
          break
      }

      form.hasAlipay = true

      return form
    },
    filterMobilePayment(tempForm) {
      let form = {}
      if (!tempForm.mobileVisible) return {}

      form.smsMchId = tempForm.smsMchId
      form.hasMobilePayment = true

      return form
    },
    tranformChannelsToArray(paymentChannels) {
      if (!isString(paymentChannels)) return []
      return paymentChannels.split(',').map((item) => item)
    },
    changeHidden(label, hidden, rules = []) {
      const item = this.items.find((item) => {
        return item.label === label
      })

      if (!item) return

      item.hidden = hidden

      if (item.value == 'refund') return

      if (hidden) {
        delete this.rules[item.value]

        this.$set(this.rules, item.value, [])
      } else {
        this.$set(this.rules, item.value, [
          {
            required: true,
            message: `请输入${item.label}`,
          },
          ...rules,
        ])
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.merchant-detail-payment_bottom {
  border-bottom: 1px solid #000;
}
</style>
